package app.server.project.main.service.service.recharge;

import app.server.project.core.http.CMSLstResp;
import app.server.project.main.service.db.dao.cfg.RechargeCfgDao;
import app.server.project.main.service.db.entity.cfg.RechargeCfgEntity;
import app.server.project.main.service.service.cms.GMService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Comparator;

@AllArgsConstructor
@Service
public class RechargeCfgService {
    private RechargeCfgDao rechargeCfgDao;
    private GMService gmService;

    public CMSLstResp<RechargeCfgEntity> getAll() {
        var list = this.rechargeCfgDao.listOrderByType();
        return CMSLstResp.of(list, list.size());
    }

    public CMSLstResp<RechargeCfgEntity> getStore() {
        var list = this.rechargeCfgDao.getStore();
        return CMSLstResp.of(list, list.size());
    }

    public void save(RechargeCfgEntity rechargeCfgEntity) {
        var list = this.rechargeCfgDao.list();
        rechargeCfgEntity.setId(list.stream().max(Comparator.comparingInt(RechargeCfgEntity::getId)).get().getId() + 1);
        this.rechargeCfgDao.save(rechargeCfgEntity);
        this.rechargeCfgDao.init();
    }

    public void edit(RechargeCfgEntity rechargeCfgEntity) {
        this.rechargeCfgDao.saveOrUpdate(rechargeCfgEntity);
        this.rechargeCfgDao.init();
    }

    public void del(RechargeCfgEntity rechargeCfgEntity) {
        this.rechargeCfgDao.removeById(rechargeCfgEntity.getId());
        this.rechargeCfgDao.init();
    }

    public void uploadImg(MultipartFile files, int rechargeCfgId) {
        var imgUrl = this.gmService.uploadSingleImg(files);
        var raceCfg = this.rechargeCfgDao.getDataById(rechargeCfgId);
        raceCfg.setImgUrl(imgUrl);
        this.rechargeCfgDao.saveOrUpdate(raceCfg);
        this.rechargeCfgDao.init();
    }

    public void uploadSku(MultipartFile files, int rechargeCfgId) {
        var imgUrl = this.gmService.uploadSingleImg(files);
        var raceCfg = this.rechargeCfgDao.getDataById(rechargeCfgId);
        raceCfg.setSkuUrl(imgUrl);
        this.rechargeCfgDao.saveOrUpdate(raceCfg);
        this.rechargeCfgDao.init();
    }
}
